<template>
  <div>
    <!-- 功能按钮 -->
    <el-form class="tableSearch" size="mini">
      <el-form-item>
        <el-button type="primary" @click="$router.back(-1)">返回</el-button>
        <el-button
          type="primary"
          v-if="setRole('修改')"
          v-show="showTab=='1' && canEdit == true"
          @click="handleEdit()"
        >修改</el-button>
        <el-button type="primary" v-show="showTab=='2'" @click="submitForm('formdata')">保存</el-button>
        <el-button
          type="primary"
          v-if="setRole('关闭采购订单')"
          v-show="showTab=='1' && canClose == true"
          @click="handleOrderDeal(7)"
        >关闭单据</el-button>
        <el-button
          type="primary"
          v-if="setRole('取消采购订单')"
          v-show="showTab=='1' && canCancel == true"
          @click="handleOrderDeal(4)"
        >取消单据</el-button>
        <el-button type="primary" v-show="showTab=='2'" @click="openGoodsdialog()">批量添加商品</el-button>
        <el-button
          type="primary"
          v-show="showTab=='2'"
          @click="selectTable.handleMultipleDel()"
        >批量删除商品</el-button>
      </el-form-item>
    </el-form>

    <!-- form表单 -->
    <el-form :model="formdata" label-width="120px" :rules="rules" ref="formdata" size="mini">
      <el-row>
        <el-col :span="8">
          <el-form-item label="指定供应商：" prop="supplierName">
            <span v-show="showTab == '1'">{{formdata.supplierName}}</span>
            <el-input v-show="showTab == '2'" v-model="formdata.supplierName" disabled>
              <el-button type="primary" @click="openSuppDialog()" slot="append">选择</el-button>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="收货日期：" prop="receiveDate">
            <span v-show="showTab == '1'">{{formdata.receiveDate}}</span>
            <el-date-picker
              v-show="showTab == '2'"
              v-model="formdata.receiveDate"
              format="yyyy年 MM 月 dd 日"
              value-format="yyyy-MM-dd"
              type="date"
              placeholder="选择收货日期"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="订单状态：">
            <span v-show="showTab == '1'">{{orderStatusArr[formdata.statusFlow]}}</span>
            <el-input
              v-show="showTab == '2'"
              v-model="orderStatusArr[formdata.statusFlow]"
              disabled
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="单据日期：">
            <span v-show="showTab == '1'">{{formdata.orderDate}}</span>
            <el-date-picker
              v-show="showTab == '2'"
              v-model="formdata.orderDate"
              format="yyyy年 MM 月 dd 日"
              value-format="yyyy-MM-dd"
              type="date"
              disabled
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="单据编号：">
            <span v-show="showTab == '1'">{{formdata.purchaseCode}}</span>
            <el-input v-show="showTab == '2'" v-model="formdata.purchaseCode" disabled></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 表格 -->
    <el-table :data="selectTable.tableData" @selection-change="selectTable.handleMultipleSelect">
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column type="index" label="#" width="55"></el-table-column>
      <el-table-column prop="goodsCode" label="商品货号" align="center"></el-table-column>
      <el-table-column prop="barCode" label="商品条码" align="center"></el-table-column>
      <el-table-column prop="goodsName" label="商品" align="center" width="200"></el-table-column>
      <!-- <el-table-column
        prop="dateInProduced"
        label="生产日期"
        align="center"
        key="1"
        v-if="(purchaseTypes=='1'||purchaseTypes=='0')&&canCancel==false"
      >
        <template slot-scope="scope">
          <span v-if="scope.row.isBatch === '1'">{{scope.row.dateInProduced}}</span>
          <span v-if="scope.row.isBatch === '0'">{{"---"}}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="goodsBatchNumber"
        label="商品批次"
        align="center"
        key="2"
        v-if="(purchaseTypes=='1'||purchaseTypes=='0')&&canCancel==false"
      >
        <template slot-scope="scope">
          <span v-if="scope.row.isBatch === '1'">{{scope.row.goodsBatchNumber}}</span>
          <span v-if="scope.row.isBatch === '0'">{{"---"}}</span>
        </template>
      </el-table-column> -->
      <el-table-column prop="unitName" label="单位" align="center"></el-table-column>
      <el-table-column prop="goodsSpec" label="规格型号" align="center">
        <template slot-scope="scope">
          <div v-for="(item, index) in scope.row.goodsSpec" :key="index">
            <span>{{item.paramName}} :</span>
            <span>{{item.paramValue}}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="price" label="单价" align="center"></el-table-column>
      <el-table-column prop="goodsNum" label="数量" align="center" width="150">
        <template slot-scope="scope">
          <span v-show="showTab == '1'">{{scope.row.goodsNum}}</span>
          <input
            class="commonInput"
            v-show="showTab == '2'"
            v-model="scope.row.goodsNum"
            size="mini"
            type="text"
            style="width:100px"
            value="1"
            min="0"
            maxlength="8"
            oninput="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else{this.value=this.value.replace(/\D/g,'')}"
            onafterpaste="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'0')}else{this.value=this.value.replace(/\D/g,'')}"
          />
        </template>
      </el-table-column>
            <el-table-column prop="goodsPrice" label="销售价"  v-if="(purchaseTypes=='1'||purchaseTypes=='0')&&canCancel==false" align="center"></el-table-column>
      <el-table-column
        prop="goodsAmount"
        label="总价"
        align="center"
        v-if="purchaseTypes=='2'||canCancel==true"
      >
        <template slot-scope="scope">
          <span>{{(scope.row.goodsPrice*scope.row.goodsNum).toFixed(2)}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="confirmNum" label="采购确认数量" align="center"></el-table-column>
      <el-table-column v-if="showTab == '2'" align="center" label="操作">
        <template slot-scope="scope">
          <el-button type="text" @click="selectTable.handleSingleDel(scope.$index)" size="mini">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 费用表单 -->
    <el-form :model="formdata" label-width="120px" size="mini" style="margin-top:25px;">
      <el-row>
        <el-col :span="4">&nbsp;</el-col>
        <el-col :span="6">
          <el-form-item label="操作员：">
            <span v-show="showTab == '1'">{{formdata.userName}}</span>
            <el-input v-show="showTab == '2'" v-model="formdata.userName" disabled></el-input>
          </el-form-item>
          <el-form-item label="备注：">
            <span v-show="showTab == '1'">{{formdata.remark}}</span>
            <el-input
              v-show="showTab == '2'"
              v-model="formdata.remark"
              type="textarea"
              maxlength="50"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="总计：">
            <span v-show="showTab == '1'">{{formdata.purchaseAmount}}</span>
            <el-input v-show="showTab == '2'" v-model="formdataTotal" disabled></el-input>
          </el-form-item>
          <el-form-item label="运费：">
            <span v-show="showTab == '1'">{{formdata.freight}}</span>
            <sd-input v-show="showTab == '2'" :val.sync="formdata.freight"></sd-input>
          </el-form-item>
          <el-form-item label="应付总计：">
            <span v-show="showTab == '1'">{{formdata.amount}}</span>
            <el-input v-show="showTab == '2'" v-model="formdataAllTotal" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="确认商品总计：">
            <span v-show="showTab == '1'">{{formdata.confirmPurchaseAmount}}</span>
            <el-input v-show="showTab == '2'" v-model="formdata.confirmPurchaseAmount" disabled></el-input>
          </el-form-item>
          <el-form-item label="确认运费：">
            <span v-show="showTab == '1'">{{formdata.confirmFreight}}</span>
            <el-input v-show="showTab == '2'" v-model="formdata.confirmFreight" disabled></el-input>
          </el-form-item>
          <el-form-item label="确认应付总计：">
            <span v-show="showTab == '1'">{{formdata.confirmAmount}}</span>
            <el-input v-show="showTab == '2'" v-model="formdata.confirmAmount" disabled></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 供应商弹出框 -->
    <el-dialog
      title="供应商选择"
      :visible.sync="supplierClass.dialog"
      :closeOnClickModal="false"
      :closeOnPressEscape="false"
    >
      <el-form label-width="0" size="mini">
        <el-form-item>
          <el-button type="primary" @click="handleSelectSupplier()">选择</el-button>
          <el-button @click="supplierClass.dialog=false">取消</el-button>
        </el-form-item>
        <el-form-item>
          <el-input v-model="selectdata.keywordSupp" placeholder="请输入供应商名称、编码" style="width:200px;">
            <i
              slot="suffix"
              class="el-input__icon el-icon-search"
              @click="supplierClass.handleSearch(_selectBaseShopPageList, supplierClass.pageData)"
            ></i>
          </el-input>
        </el-form-item>
      </el-form>
      <el-table
        :data="supplierClass.tableData"
        highlight-current-row
        @current-change="supplierClass.handleSingleSelect"
      >
        <el-table-column type="index" width="50"></el-table-column>
        <el-table-column prop="shopCode" label="供应商编码" align="center"></el-table-column>
        <el-table-column prop="name" label="供应商名称" align="center"></el-table-column>
      </el-table>
      <page-unit :pageData="supplierClass.pageData" :func="_selectBaseShopPageList"></page-unit>
    </el-dialog>

    <!-- 商品选择弹出框 -->
    <el-dialog
      title="商品选择"
      :visible.sync="goodsClass.dialog"
      :closeOnClickModal="false"
      :closeOnPressEscape="false"
    >
      <el-form label-width="0" size="mini">
        <el-form-item>
          <el-button type="primary" @click="handleSelectGoods()">选择</el-button>
          <el-button @click="goodsClass.dialog=false">取消</el-button>
          <el-alert
            title="未创建价格协议的商品不可选择!"
            center
            type="error"
            :closable="false"
            style="display:inline;padding:4px 8px;"
          ></el-alert>
        </el-form-item>
        <el-form-item>
          <el-input v-model="selectdata.keywordGoods" placeholder="输入商品名称或编号" style="width:200px;">
            <i
              slot="suffix"
              class="el-input__icon el-icon-search"
              @click="goodsClass.handleSearch(_findOrderPriceAgreementListPage, goodsClass.pageData)"
            ></i>
          </el-input>
        </el-form-item>
      </el-form>
      <el-table
        :data="goodsClass.tableData"
        tooltip-effect="dark"
        @selection-change="goodsClass.handleMultipleSelect"
        :row-key="goodsClass.getRowKeys"
      >
        <el-table-column type="selection" width="55" :reserve-selection="true"></el-table-column>
        <el-table-column prop="goodsName" label="商品" align="center"></el-table-column>
        <el-table-column prop="purchaseUnit" label="单位" align="center"></el-table-column>
        <el-table-column prop="goodsCode" label="商品货号" align="center"></el-table-column>
        <el-table-column prop="barCode" label="商品条码" align="center"></el-table-column>
        <el-table-column prop="supplierName" label="供应商名称" align="center" width="120"></el-table-column>
        <el-table-column prop="parameter" label="规格型号" align="center" width="150">
          <template slot-scope="scope">
            <div v-for="(item,index) in scope.row.goodsSpec" :key="index">
              <span v-if="item!=null">{{item.paramName}} :</span>
              <span v-if="item!=null">{{item.paramValue}}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="isFreight" label="含运费" align="center">
          <template slot-scope="scope">
            <span v-show="scope.row.isFreight=='1'">含运费</span>
            <span v-show="scope.row.isFreight=='0'">不含运费</span>
          </template>
        </el-table-column>
        <el-table-column prop="freight" label="运费" align="center"></el-table-column>
        <el-table-column prop="goodsPrice" label="价格" align="center"></el-table-column>
      </el-table>
      <page-unit :pageData="goodsClass.pageData" :func="_findOrderPriceAgreementListPage"></page-unit>
    </el-dialog>
  </div>
</template>

<script>
import SdInput from "@/components/SdInput";
import { mapState } from "vuex";
import pageUnit from "@/components/Page";
import state from "@/util/state";
import util from "@/util";
import { TableHandle } from "@/util/class";
import {
  getGoodsPurchaseDetails,
  findOrderPriceAgreementListPage,
  selectBaseShopPageList,
  updateGoodsPurchase
} from "@/api";

export default {
  components: { SdInput, pageUnit },

  data() {
    return {
      selectdata: {
        keywordGoods: "", // 商品搜索关键字
        keywordSupp: "" // 供应商搜索关键字
      },
      orderStatusArr: state.orderStatusArr, // 订单状态
      id: "", // 查看详情主键id
      showTab: "", // 查看/修改
      canClose: false, // 是否显示关闭单据按钮
      canCancel: false, // 是否显示取消单据按钮
      canEdit: false, // 是否显示修改单据按钮
      rules: {
        supplierName: [
          { required: true, message: "请选择供应商", trigger: "blur" }
        ],
        receiveDate: [
          { required: true, message: "请选择收货时间", trigger: "blur" }
        ]
      },
      formdata: {
        supplierId: "", // 供应商id
        supplierName: "", // 供应商名称
        receiveDate: "", // 收货日期
        statusFlow: "", // 订单状态
        orderDate: "", // 单据日期
        purchaseCode: "", // 单据编号
        userName: "", // 操作员
        remark: "", // 备注
        purchaseAmount: 0, // 总计
        freight: 0, // 运费
        amount: 0 // 应付总计
      },
      supplierClass: new TableHandle(), // 供应商弹窗对象
      goodsClass: new TableHandle(), // 商品弹窗对象
      selectTable: new TableHandle(), // 弹窗选择后的商品数组
      purchaseTypes: "" //是否自建
    };
  },

  computed: {
    ...mapState({
      merchantId: state => state.merchantId,
      power: state => state.power,
      userId: state => state.userId
    }),

    // 总计自动计算
    formdataTotal: function() {
      let priceItem = 0,
        freightItem = 0;
      this.selectTable.tableData.forEach(i => {
        i.goodsAmount = Number(i.goodsPrice) * Number(i.goodsNum);
        priceItem += i.goodsAmount;
        if (Number(i.isFreight) === 0) {
          freightItem += Number(i.freight) * Number(i.goodsNum);
        }
      });
      this.formdata.purchaseAmount = isNaN(priceItem)
        ? 0
        : priceItem.toFixed(2);
      this.formdata.freight = isNaN(freightItem) ? 0 : freightItem.toFixed(2);
      return this.formdata.purchaseAmount;
    },

    // 应付总计自动计算
    formdataAllTotal: function() {
      return (
        Number(this.formdata.purchaseAmount) + Number(this.formdata.freight)
      ).toFixed(2);
    }
  },

  created() {
    this.id = util.getQuery().id;
    this.showTab = util.getQuery().showTab;
  },

  mounted() {
    this._getGoodsPurchaseDetails();
  },

  methods: {
    // 分配权限
    setRole(key) {
      return util.selectTitle(this.power, key);
    },

    // 根据id查看详情
    _getGoodsPurchaseDetails() {
      getGoodsPurchaseDetails({
        id: this.id
      }).then(res => {
        this.formdata = res.data;
        this.purchaseTypes = res.data.purchaseType;
        this.selectTable.tableData = res.data.goodsList;
        this.formdata.orderDate = util.getdatetime(this.formdata.orderDate);
        this.formdata.receiveDate = util.getdatetime(this.formdata.receiveDate);
        // 是否显示修改单据按钮
        if (this.formdata.statusFlow == 0 || this.formdata.statusFlow == 2) {
          this.canEdit = true;
        }
        // 是否显示关闭单据按钮
        if (this.formdata.statusFlow == 5) {
          this.canClose = true;
        }
        // 是否显示取消单据按钮
        if (
          this.formdata.statusFlow == 0 ||
          this.formdata.statusFlow == 1 ||
          this.formdata.statusFlow == 2 ||
          this.formdata.statusFlow == 3
        ) {
          this.canCancel = true;
        }
        let freight = res.data.freight;
        this.$nextTick(() => {
          this.formdata.freight = freight;
        });
      });
    },

    // 点击修改
    handleEdit() {
      this.showTab = "2";
    },

    // 关闭/取消单据
    handleOrderDeal(type) {
      this.$delete(this.formdata, "statusFlow");
      this.$set(this.formdata, "statusFlow", type);
      this.handleSave();
    },

    // 打开供应商弹窗
    openSuppDialog() {
      this._selectBaseShopPageList(this.supplierClass.pageData.pageSize, 1);
      this.supplierClass.dialog = true;
    },

    // 获取供应商数据api
    _selectBaseShopPageList(pageSize, pageNum) {
      selectBaseShopPageList({
        nameOrCode: this.selectdata.keywordSupp,
        pageSize: pageSize,
        pageNum: pageNum,
        status: 0,
        businessId: this.merchantId,
        type: 2
      }).then(res => {
        this.supplierClass.tableData = res.data.list;
        this.supplierClass.pageData.totalItems = res.data.pageTotal;
      });
    },

    // 供应商弹窗点击选择
    handleSelectSupplier() {
      if (this.supplierClass.isSelect(1, this, "请先选择供应商！")) {
        this.formdata.supplierName = this.supplierClass.singleSelectTable.name;
        this.formdata.supplierId = this.supplierClass.singleSelectTable.id;
        this.supplierClass.dialog = false;
      }
    },

    // 打开商品弹窗
    openGoodsdialog() {
      this._findOrderPriceAgreementListPage(
        this.goodsClass.pageData.pageSize,
        1
      );
      this.goodsClass.dialog = true;
    },

    // 获取商品数据api
    _findOrderPriceAgreementListPage(pageSize, pageNum) {
      findOrderPriceAgreementListPage({
        keyword: this.selectdata.keywordGoods,
        pageSize: pageSize,
        pageNum: pageNum,
        supplierId: this.formdata.supplierId,
        customerId: this.merchantId,
        status: 0,
        agreementType: 1 //协议类型：0-销售价格协议，1-采购价格协议
      }).then(res => {
         res.data.list.forEach(e=>{
          e.price=e.goodsPrice
        })
        this.goodsClass.tableData = res.data.list;
        this.goodsClass.pageData.totalItems = res.data.pageTotal;
      });
    },

    // 商品弹窗点击选择
    handleSelectGoods() {
      if (this.goodsClass.isSelect(2, this, "请先选择商品！")) {
        this.goodsClass.multipleSelectTable.forEach(i => {
          i.purchaseAmount = 0;
          i.goodsNum = 0;
          i.isFreight = 0;
          i.unitName = i.purchaseUnit;
        });
        this.selectTable.tableData = this.goodsClass.handleMultipleConfirm(
          this.selectTable.tableData,
          "goodsId"
        );
        this.goodsClass.dialog = false;
      }
    },

    // 提交表单
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.handleSave();
        } else {
          return false;
        }
      });
    },

    // 提交表单数据
    handleSave() {
      if (this.selectTable.tableData.some(i => i.goodsNum < i.minNum)) {
        this.$message.error("数量不能小于最小起订数量");
        return false;
      }
      this.selectTable.tableData.forEach(i => {
        delete i.createTime;
        delete i.updateTime;
      });
      // return
      updateGoodsPurchase({
        id: this.id,
        shopId: this.merchantId,
        supplierId: this.formdata.supplierId,
        supplierName: this.formdata.supplierName,
        receiveDate: this.formdata.receiveDate,
        orderDate: this.formdata.orderDate,
        statusFlow: this.formdata.statusFlow,
        purchaseinCode: this.formdata.purchaseCode,
        remark: this.formdata.remark,
        purchaseAmount: this.formdata.purchaseAmount,
        freight: this.formdata.freight,
        amount: this.formdataAllTotal,
        creator: this.userId,
        goodsList: JSON.stringify(this.selectTable.tableData)
      }).then(res => {
        if (res.code == 200) {
          this.$message.success(res.msg);
          history.back();
        }
      });
    }
  }
};
</script>

<style lang="less">
.el-input-group__append {
  background-color: #409eff;
  border-color: #409eff;
  color: #ffffff;
}

.el-dialog__header {
  background-color: #25a0e9;
  .el-dialog__title {
    color: #ffffff;
  }
  .el-dialog__close {
    color: #ffffff;
    &:hover {
      &:before {
        color: #ffffff;
      }
    }
  }
}
</style>
